<?php

namespace App\Http\Controllers\Admin;

use App\Rules\CheckPic;
use App\Http\Models\Product;
use Illuminate\Http\Request;
use App\Http\Models\Category;
use App\Http\Services\Upload;
use App\Http\Controllers\Controller;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $product = Product::OrderBy("created_at","desc")->OrderBy("id","desc")->paginate(10);
        return view("admin.product.index",compact('product'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $cates = Category::getCates();
        return view("admin.product.create",compact('cates'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request,Product $product,Upload $upload)
    {
        $request->validate([
            'cid'      => 'required|integer',
            'title'    => 'required',
            'remark'   => 'required',
            'pic'      => ['required',new CheckPic($request['pic'])],
            'contents' => 'required'
        ]);

        $product->cid     = $request['cid'];
        $product->title   = $request['title'];
        $product->keyword = $request['keyword'];
        $product->desc    = $request['desc'];
        $product->remark  = $request['remark'];
        $product->views   = $request['views'];
        $product->incom   = isset($request['incom']) ? $request['incom'] : 0;
        $product->pic     = $upload->store($request['pic'],"product")[0];
        $product->content = $request['contents'];

        checkReturn($product->save(),"创建成功");
        return redirect(route('admin.product.create'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Product $product)
    {
        $cates = Category::getCates();
        return view("admin.product.edit",compact('cates','product'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        dd($request->all());
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
